import { ElNotification, ElMessage } from "element-plus";

class WS {
  private socket: WebSocket | null = null;
  private url: string;
  private messageCallbacks: Array<(data: any) => void> = [];
  private errorCallbacks: Array<(error: Event) => void> = [];
  private closeCallbacks: Array<(event: CloseEvent) => void> = [];
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 10;
  private reconnectInterval = 5000; // 5秒
  private reconnectTimer: number | null = null;
  private isManualClose = false;

  constructor() {
    this.url = import.meta.env.VITE_WS_PREFIX;
  }

  // WS连接
  private connect(value: any): void {
    this.url += "?token=" + value;
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log("WebSocket连接成功");
      this.reconnectAttempts = 0;
    };

    this.socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        messageHandler(data);
        this.messageCallbacks.forEach((callback) => callback(data));
      } catch (error) {
        console.error("消息解析错误:", error);
      }
    };

    this.socket.onerror = (error) => {
      console.error("WebSocket错误:", error);
      this.errorCallbacks.forEach((callback) => callback(error));
    };

    this.socket.onclose = (event) => {
      console.log("WebSocket连接关闭");
      this.closeCallbacks.forEach((callback) => callback(event));

      if (
        !this.isManualClose &&
        this.reconnectAttempts < this.maxReconnectAttempts
      ) {
        this.reconnect();
      }
    };
  }

  // 自动重连
  private reconnect(): void {
    this.reconnectAttempts++;
    console.log(`尝试第 ${this.reconnectAttempts} 次重连...`);

    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }

    this.reconnectTimer = window.setTimeout(() => {
      this.connect(this.url);
    }, this.reconnectInterval);
  }

  // 发送消息
  send(data: any): void {
    if (this.socket?.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data));
    } else {
      console.error("WebSocket未连接，无法发送消息");
      // 可选：将消息加入队列，等重连成功后发送
    }
  }

  // 添加消息监听
  onMessage(callback: (data: any) => void): void {
    this.messageCallbacks.push(callback);
  }

  // 添加错误监听
  onError(callback: (error: Event) => void): void {
    this.errorCallbacks.push(callback);
  }

  // 添加关闭监听
  onClose(callback: (event: CloseEvent) => void): void {
    this.closeCallbacks.push(callback);
  }

  // 启动连接
  startConnection(value: any): void {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      console.warn("WebSocket已连接");
      return;
    }
    this.isManualClose = false; // 重置手动关闭标志
    this.connect(value);
  }

  // 关闭连接
  closeConnection(): void {
    this.isManualClose = true;
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
    this.socket?.close();
    ElMessage.warning("WebSocket连接已关闭");
  }

  // 获取连接状态
  getState(): string {
    if (!this.socket) return "未初始化";

    switch (this.socket.readyState) {
      case WebSocket.CONNECTING:
        return "连接中";
      case WebSocket.OPEN:
        return "已连接";
      case WebSocket.CLOSING:
        return "关闭中";
      case WebSocket.CLOSED:
        return this.isManualClose ? "手动关闭" : "已断开";
      default:
        return "未知状态";
    }
  }
}

function messageHandler(message: any) {
  if (message.type === "SYSTEM_MESSAGE") {
    // ElNotification({
    //   position: "bottom-right",
    //   title: "系统消息",
    //   message: message.message,
    // });
    ElMessage({
      type: "success",
      message: "WebSocket" + message.message,
    });
  } else if (message.type === "MESSAGE") {
    ElNotification({
      position: "bottom-right",
      title: "消息",
      message: message.message,
    });
  }
}

export default WS;
